package com.ls.controller;

import com.ls.annotation.LoginRequired;
import com.ls.entity.Event;
import com.ls.entity.User;
import com.ls.event.EventProducer;
import com.ls.service.LikeService;
import com.ls.util.CommunityConstant;
import com.ls.util.UserContextHolder;
import com.ls.util.R;
import com.ls.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author ls
 * @date 2021/1/5
 **/
@Controller
public class LikeController implements CommunityConstant {

    @Autowired
    private LikeService likeService;

    @Autowired
    private UserContextHolder userContextHolder;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 点赞功能
     *
     * @param entityType   实体类型
     * @param entityId     实体id
     * @param entityUserId 实体用户id
     * @return
     */
    @LoginRequired
    @PostMapping("/like")
    @ResponseBody
    public R like(int entityType, int entityId, int entityUserId, int postId) {
        User user = userContextHolder.getUser();

        // 点赞
        likeService.like(user.getId(), entityType, entityId, entityUserId);

        // 点赞数量
        long likeCount = likeService.getEntityLikeCount(entityType, entityId);
        // 点赞状态
        int likeStatus = likeService.getEntityLikeStatus(user.getId(), entityType, entityId);

        // 触发点赞事件
        // 点赞
        if (likeStatus == 1) {
            Event event = new Event()
                    .setTopic(TOPIC_LIKE)
                    .setUserId(user.getId())
                    .setEntityType(entityType)
                    .setEntityId(entityId)
                    .setEntityUserId(entityUserId)
                    .setData("postId", postId);
            eventProducer.fireEvent(event);
        }

        // 对帖子点赞, 计算帖子分数
        if (entityType == ENTITY_TYPE_POST) {
            String redisKey = RedisKeyUtil.getPostScoreKey();
            redisTemplate.opsForSet().add(redisKey, postId);
        }

        // 返回的结果
        return R.ok().put("likeCount", likeCount).put("likeStatus", likeStatus);
    }

}
